package nl.windgazer.arachne.services.messages;

import java.lang.annotation.Annotation;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.apache.tapestry5.Binding;
import org.apache.tapestry5.services.Environment;

public class MessageBindingInterceptor implements Binding {

	private static final Logger logger = Logger.getLogger(MessageBindingInterceptor.class);

	private Binding binding;
	private Environment environment;
	private String expression;

	private Locale locale;

	public MessageBindingInterceptor(Binding binding, Environment environment, String expression, Locale locale) {
		this.binding = binding;
		this.environment = environment;
		this.expression = expression;
		this.locale = locale;
	}

	public Object get() {
		Object value = binding.get();
		
		if (environment != null) {
			MessageInterceptEventListener listener = environment.peek(MessageInterceptEventListener.class);
			if (listener!=null) {
				return listener.intercept(expression, value.toString(), locale);
			} else {
				logger.error("Cannot enrich message '" + expression + "', no listener available in environment :(.");
			}
		} else {
			logger.error("Cannot enrich message '" + expression + "', no environment available.");
		}
		return value;
	}

	@SuppressWarnings("rawtypes")
	public Class getBindingType() {
		return binding.getBindingType();
	}

	/**
	 * We don't want components to cache the value, that would prevent us from being able to tag the html...
	 */
	public boolean isInvariant() {
		return false;
	}

	public void set(Object arg0) {
		binding.set(arg0);
	}

	public <T extends Annotation> T getAnnotation(Class<T> arg0) {
		return binding.getAnnotation(arg0);
	}

}
